from group import Group


def write_groups_to_json(path, groups):
    import json

    data = []
    for key in groups:
        group = groups.get(key)
        jsonData = json.dumps({key: {"count": group.countArray, "simiSum": group.simiSumArray}})
        data.append(jsonData)
        data.append("\n")

    with open(path, "w", encoding="utf-8") as file:
        for item in data:
            file.write(item)


def read_json_to_groups(path):
    import json

    groups = {}
    with open(path, "r", encoding="utf-8") as file:
        for jsonStr in file.readlines():
            jsonData = json.loads(jsonStr)
            key = list(jsonData.keys())[0]
            value = jsonData[key]
            countArray = value["count"]
            simiSumArray = value["simiSum"]
            groups[key] = Group(key.split(":")[0], key.split(":")[1], countArray, simiSumArray)

    return groups